package com.starblink.message.messageactivities.ui

import android.graphics.Bitmap
import android.graphics.Color
import android.widget.TextView
import com.alibaba.android.arouter.facade.annotation.Route
import com.bumptech.glide.load.MultiTransformation
import com.starblink.android.basic.base.activity.BaseTVMActivity
import com.starblink.android.basic.bean.LoadAction
import com.starblink.android.basic.brv.utils.divider
import com.starblink.android.basic.brv.utils.linear
import com.starblink.android.basic.brv.utils.models
import com.starblink.android.basic.brv.utils.setup
import com.starblink.basic.apollo.ext.ApolloValSetExt.apolloValue
import com.starblink.android.basic.ext.dp
import com.starblink.android.basic.ext.toast
import com.starblink.android.basic.ext.visibleOrGone
import com.starblink.android.basic.extension.navigationTo
import com.starblink.android.basic.sensorsdata.room.entity.SkAntEntity
import com.starblink.android.basic.sensorsdata.spm.GTrackerAssistUtils
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmElementDef
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmPageDef
import com.starblink.android.basic.sensorsdata.spm.impl.SpmTrackHandler
import com.starblink.android.basic.util.ImageUtils
import com.starblink.android.basic.util.bus.FlowBus
import com.starblink.android.basic.util.bus.FlowConst
import com.starblink.android.basic.util.post.PostUtils
import com.starblink.basic.route.RoutePage
import com.starblink.basic.style.title.OnTitleBarListener
import com.starblink.basic.style.title.TitleBar
import com.starblink.message.Constants
import com.starblink.message.MessageManager
import com.starblink.message.databinding.ActivityMessageActivitiesBinding
import com.starblink.message.databinding.ItemMessageActivityBinding
import com.starblink.rocketreserver.FetchSystemMessageQuery
import jp.wasabeef.glide.transformations.RoundedCornersTransformation

/**
 * 活动消息页
 */
@Route(path = RoutePage.Message.MESSAGE_ACTIVITY, extras = RoutePage.Extra.NEED_LOGIN)
class MessageActivitiesActivity :
    BaseTVMActivity<ActivityMessageActivitiesBinding, MessageActivitiesVM>() {
    private val glideTransformation = MultiTransformation<Bitmap>(
        RoundedCornersTransformation(16.dp, 0, RoundedCornersTransformation.CornerType.TOP)
    )

    override fun initViewBinding(): ActivityMessageActivitiesBinding =
        ActivityMessageActivitiesBinding.inflate(layoutInflater)

    override fun initView() {
        super.initView()
        // 埋点：页面曝光
        pageExposure(pageElementValue = SpmPageDef.MESSAGE_ACTIVITIES)

        viewBinding.titleBar.setOnTitleBarListener(object : OnTitleBarListener {
            override fun onLeftClick(titleBar: TitleBar?) {
                finish()
            }
        })

        viewBinding.rv.linear().divider {
            setColor(Color.TRANSPARENT)
            setDivider(8, true)
            startVisible = false
            endVisible = true
        }.setup {
            addType<FetchSystemMessageQuery.FetchSystemMessage, ItemMessageActivityBinding>(it)

            onBind {
                val viewBinding = getBinding<ItemMessageActivityBinding>()
                val model =
                    getModel<FetchSystemMessageQuery.FetchSystemMessage>()

                model.apply {
                    // 消息曝光即已读，调接口通知服务器
                    if (model.status == Constants.MessageStatus.UNREAD && id != null) {
                        apolloValue("status", Constants.MessageStatus.READED)
                        MessageManager.readSystemMessage(
                            context,
                            messageId = id!!
                        ) {}
                    }

                    pushTime?.apply {
                        viewBinding.tvTime.text =
                            PostUtils.getTimeDiffDetailFriendly(pushTime as String)
                    }

                    viewBinding.ivPostMainPic.visibleOrGone(!mainPic.isNullOrEmpty()) {
                        ImageUtils.loadImage(
                            this@MessageActivitiesActivity,
                            mainPic,
                            this,
                            ImageUtils.errorImage2,
                            ImageUtils.errorImage2,
                            glideTransformation
                        )
                    }

                    viewBinding.tvTitle.visibleOrGone(!title.isNullOrEmpty()){
                        text = title
                    }
                    viewBinding.divier.visibleOrGone(mainPic.isNullOrEmpty() && !title.isNullOrEmpty())

                    viewBinding.tvContent.text = content ?: ""

                    viewBinding.root.setOnClickListener {
                        if (status == Constants.MessageStatus.DELETED) {
                            toast("This message was deleted.")
                            return@setOnClickListener
                        }
                        // 埋点：站内信页面-消息点击
                        SpmTrackHandler.addSingleTrackData(
                            SkAntEntity(
                                spmCnt = GTrackerAssistUtils.fetchElementValue(
                                    SpmPageDef.MESSAGE_ACTIVITIES,
                                    SpmElementDef.ACTIVITY_MESSAGE_CLICK
                                ),
                                params = mapOf("title" to (title ?: ""))
                            )
                        )
                        //跳转类型，1：话题活动，2：链接
                        if (jumpType == 1 && !hashtagId.isNullOrEmpty()) {
                            navigationTo(RoutePage.Post.PAGE_TOPIC) {
                                withString(RoutePage.Post.TOPIC_ID, hashtagId)
                            }
                        } else if (jumpType == 2 && !jumpUrl.isNullOrEmpty()) {
                            navigationTo(RoutePage.Web.PAGE_GLOBAL_H5) {
                                withString(RoutePage.Web.ARG_URL, jumpUrl!!)
                                withString(RoutePage.Web.ARG_TITLE, title ?: "")
                            }
                        }
                    }
                }
            }
        }
        viewBinding.page.onEmpty {
            val tvMsg = findViewById<TextView>(com.starblink.basic.style.R.id.msg)
            tvMsg.text = "Oops! It's empty here!"
        }
        viewBinding.page.onRefresh {
            viewModel.getActivityMessageList(refresh = true)
        }
        viewBinding.page.onLoadMore {
            viewModel.getActivityMessageList(refresh = false)
        }
    }

    override fun initObservable() {
        super.initObservable()
        viewModel.listResponseLiveData.observe(this)
        {
            if (viewBinding.rv.models.isNullOrEmpty() || it.refresh) {
                // 刷新或页面销毁恢复
                viewBinding.page.addData(ArrayList(it.totalList)) {
                    it.totalList.isNotEmpty()
                }
            } else {
                // 加载更多
                viewBinding.page.addData(it.pageList) {
                    it.pageList.isNotEmpty()
                }
            }
        }
        viewModel.mLoadActionLiveData.observe(this) {
            when (it.action) {
                LoadAction.STATE_ERROR -> {
                    viewBinding.page.showError()
                }
            }
        }
    }

    override fun initLoad() {
        super.initLoad()
        viewBinding.page.showLoading(refresh = true)
    }

    override fun onDestroy() {
        super.onDestroy()
        // 关闭页面时，发送消息，通知[首页-我的]页面重新加载未读消息数量
        FlowBus.boolFlowBusNotify(FlowConst.UPDATE_MESSAGE_UNREAD_COUNT_EVENT)
    }
}